package com.diaohw.platform.framework.web.util;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @author 刁海文
 * @since 2023/11/29 20:39
 */
public class RequestUtil {

    public static HttpServletRequest getRequest() {
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attr != null;
        return attr.getRequest();
    }

    public static HttpServletResponse getResponse() {
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attr != null;
        return attr.getResponse();

    }


    /**
     * 文件下载
     *
     * @param stream      文件输入流
     * @param contentType 文件类型
     * @param filename    文件名称
     * @param length      文件大小
     */
    public static void download(InputStream stream, String contentType, String filename, long length) {
        try {
            HttpServletResponse response = getResponse();
            response.setCharacterEncoding("UTF-8");
            response.setContentType(contentType);
            response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8));
            response.setContentLengthLong(length);
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] b = new byte[1024];
            int len;
            //从输入流中读取一定数量的字节，并将其存储在缓冲区字节数组中，读到末尾返回-1
            while ((len = stream.read(b)) > 0) {
                outputStream.write(b, 0, len);
            }

            stream.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
